package logic

import (
	"context"
	"errors"
	"userrpc/models/mysql"
	"userrpc/models/redis"
	"userrpc/pkg"

	"userrpc/internal/svc"
	"userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Rdb.Get("sendSmsregister" + in.Tel)

	if get.Val() == "" {
		return nil, errors.New("暂未获取短信验证码")
	}
	if get.Val() != in.SendSmsCode {
		return nil, errors.New("短信验证码输入错误")
	}

	user := mysql.User{
		Tel:      in.Tel,
		Password: pkg.Md5(in.Tel),
		NickName: in.Tel,
	}
	err := user.Register()
	if err != nil {
		return nil, errors.New("注册失败")
	}

	redis.Rdb.Del("sendSmsregister" + in.Tel)

	return &userrpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
